package com.shrw.duke.serialport.utils;


import com.shrw.duke.serialport.common.PortArg;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidParameterException;

import serial.utils.SerialPort;

/**
 * Created by rw-duke on 2017/10/24.
 */

public class SearialPortUtils {
    private static SearialPortUtils instance;
    private SerialPort mSerialPort;

    private SearialPortUtils() {
    }

    public static SearialPortUtils getInstance() {
        if (instance == null) {
            synchronized (SearialPortUtils.class) {
                if (instance == null) {
                    instance = new SearialPortUtils();
                }
            }
        }
        return instance;
    }


    /**
     * 打开串口
     *
     * @return
     * @throws SecurityException
     * @throws IOException
     * @throws InvalidParameterException
     */
    public SerialPort openSerialPort() throws SecurityException, IOException, InvalidParameterException {
        String path = PortArg.device;
        int baudrate = Integer.decode(PortArg.baudrate);
        int nbits = Integer.decode(PortArg.bits);
        int nstop = Integer.decode(PortArg.nstop);
        char cVerify = PortArg.cverify.charAt(0);

        return openSerialPort(path,baudrate,nbits,nstop,cVerify);
    }

    public SerialPort openSerialPort(String device, int baudrate, int bit, int stop, char verify) throws SecurityException, IOException, InvalidParameterException {
        if (mSerialPort == null) {
            if ((device.length() == 0) || (baudrate == -1) || bit == -1
                    || stop == -1 || verify == 'C') {
                throw new InvalidParameterException();
            }
//            Log.d("012","Path:"+path+"   baudrate:"+baudrate);
			/* Open the serial port */
            mSerialPort = new SerialPort(new File(device), baudrate, bit, verify, stop, 0);
        }
        return mSerialPort;
    }

    /**
     * 关闭串口
     */
    public void closeSerialPort() {
        if (mSerialPort != null) {
            mSerialPort.close();
            mSerialPort = null;
        }
    }

    /**
     * There is no open serial port null {@code openSerialPort()}
     *
     * @return
     */
    public InputStream getInput() {
        if (mSerialPort != null) {
            return mSerialPort.getInputStream();
        }
        return null;
    }

    /**
     * There is no open serial port null {@code openSerialPort()}
     *
     * @return
     */
    public OutputStream getOutput() {
        if (mSerialPort != null) {
            return mSerialPort.getOutputStream();
        }
        return null;
    }
}
